<template>
  <div class="draw-management-list">
    <h2>抽签管理</h2>
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索比赛..."
        class="search-input"
        clearable
        @input="handleSearch"
      ></el-input>
    </div>
    
    <el-table :data="filteredMatches" style="width: 100%" v-loading="loading">
      <el-table-column prop="match_date" label="比赛日期" width="120">
        <template #default="{ row }">
          {{ formatDate(row.match_date) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="match_time" label="比赛时间" width="120">
        <template #default="{ row }">
          {{ formatTime(row.match_time) }}
        </template>
      </el-table-column>
      
      <el-table-column label="对阵" min-width="200">
        <template #default="{ row }">
          {{ row.home_school_name }} vs {{ row.away_school_name }}
        </template>
      </el-table-column>
      
      <el-table-column prop="venue_name" label="比赛场地" width="150"></el-table-column>
      
      <el-table-column label="抽签状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getDrawStatusType(row)">
            {{ getDrawStatusText(row) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <router-link :to="'/admin/match/' + row.id + '/draw'">
            <el-button type="primary" size="small">管理抽签</el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const matches = ref([])
const filteredMatches = ref([])
const searchQuery = ref('')
const loading = ref(false)

// 获取所有比赛
const fetchMatches = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:3000/api/matches')
    const matchesData = response.data
    
    // 获取每个比赛的抽签结果
    for (const match of matchesData) {
      try {
        const drawResponse = await axios.get(`http://localhost:3000/api/matches/${match.id}/draw-results`)
        match.drawResults = drawResponse.data
      } catch (error) {
        console.error('获取抽签结果失败:', error)
        match.drawResults = []
      }
    }
    
    matches.value = matchesData
    filteredMatches.value = matchesData
  } catch (error) {
    ElMessage.error('获取比赛列表失败')
    console.error('Error:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  if (!searchQuery.value) {
    filteredMatches.value = matches.value
    return
  }
  
  const query = searchQuery.value.toLowerCase()
  filteredMatches.value = matches.value.filter(match => 
    match.home_school_name.toLowerCase().includes(query) ||
    match.away_school_name.toLowerCase().includes(query) ||
    match.venue_name.toLowerCase().includes(query)
  )
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return time.substring(0, 5)
}

// 获取抽签状态
const getDrawStatusType = (match) => {
  if (!match.drawResults) return 'info'
  
  // 计算已完成抽签的桌子数量
  const drawnTables = new Set()
  const homeSchoolDraws = new Set()
  const awaySchoolDraws = new Set()
  
  match.drawResults.forEach(result => {
    if (result.school_id === match.home_school_id) {
      homeSchoolDraws.add(result.draw_number)
    } else if (result.school_id === match.away_school_id) {
      awaySchoolDraws.add(result.draw_number)
    }
    
    // 如果一个桌号在主客场都有选手，说明这个桌子抽签完成
    if (homeSchoolDraws.has(result.draw_number) && awaySchoolDraws.has(result.draw_number)) {
      drawnTables.add(result.draw_number)
    }
  })
  
  if (drawnTables.size === 0) {
    return 'info'
  } else if (drawnTables.size < 10) {
    return 'warning'
  } else {
    return 'success'
  }
}

// 获取抽签状态文本
const getDrawStatusText = (match) => {
  if (!match.drawResults) return '待抽签'
  
  // 计算已完成抽签的桌子数量
  const drawnTables = new Set()
  const homeSchoolDraws = new Set()
  const awaySchoolDraws = new Set()
  
  match.drawResults.forEach(result => {
    if (result.school_id === match.home_school_id) {
      homeSchoolDraws.add(result.draw_number)
    } else if (result.school_id === match.away_school_id) {
      awaySchoolDraws.add(result.draw_number)
    }
    
    if (homeSchoolDraws.has(result.draw_number) && awaySchoolDraws.has(result.draw_number)) {
      drawnTables.add(result.draw_number)
    }
  })
  
  if (drawnTables.size === 0) {
    return '待抽签'
  } else if (drawnTables.size < 10) {
    return `进行中 (${drawnTables.size}/10)`
  } else {
    return '已完成'
  }
}

onMounted(() => {
  fetchMatches()
})
</script>

<style scoped>
.draw-management-list {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.el-tag {
  width: 70px;
  text-align: center;
}
</style> 